<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $helpers = array('Html', 'Form', 'Session');
    var $uses = array('User', 'Group', 'Secretquestion', 'City', 'State', 'Country', 'Brand', 'BrandPermission', 'Cart', 'QadminSummary', 'Message');
    var $components = array('Session', 'Cookie', 'Captcha', 'Email');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->autoRedirect = true;
        $this->Auth->allowedActions = array('loadStateAddress', 'loadCityAddress', 'loadState', 'loadCity', 'activateuser', 'add', 'brandcheck', 'initDB', '_getPluginControllerNames', '_getPluginControllerName', '_getPluginName', '_getPluginControllerPath', '_isPlugin', '_getClassMethods', 'build_acl', 'getusername', 'register', 'captcha', 'buyersuccess', 'addsuccess', 'emailcheck', 'capcheck', 'usercheck', 'login', 'popup_login', 'genRandomString', 'forget_password', 'backstage_login', 'logout');
    }

    function common() {

        if ($this->Session->read('Auth.User.id')!="") {
            $id = $this->Session->read('Auth.User.id');
            $group = $this->User->read(null, $id);
            $this->Session->write('grouptype', $group['Group']['group_type']);
            if ($group['Group']['group_type'] == 'S-Admins') {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
            if ($group['Group']['group_type'] == 'Q-Admins') {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
            if ($group['Group']['group_type'] == 'Sellers') {
                $this->redirect(array('controller' => 'products', 'action' => 'index'));
            }

            if ($group['Group']['group_type'] == 'Buyers') {
                $this->redirect(array('controller' => 'carts', 'action' => 'view_cart'));
            }
        }
    }

    function backstage_common() {
        if ($this->Session->read('Auth.User.id')!="") {
            if ($this->Session->read('Auth.User.group_id') == 1) {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
            if ($this->Session->read('Auth.User.group_id') == 2) {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
            if ($this->Session->read('Auth.User.group_id') == 3) {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
            if ($this->Session->read('Auth.User.group_id') == 4) {
                $this->redirect(array('controller' => 'backstage', 'action' => 'index'));
            }
        }
    }

    function backstage_deshboard() {
        $this->layout = 'admin';
    }

    function login() {
        $this->layout = 'innerhome';
        $this->loadModel('Category');
        $this->loadModel('Product');
        $this->set('item', $this->Category->categoryArray());
        //$this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));        

        $uniqueIDCoookie = $this->Cookie->read('uniqueID');

        if ($this->Auth->User('id')) {
            $conditions = array('unique_id' => $uniqueIDCoookie, "status" => 0);
            $alreadyInCart = $this->Cart->find("all", array("conditions" => $conditions));
            if ($alreadyInCart) {
                $this->loadModel('BlockCountry');
                foreach ($alreadyInCart as $cart):
                    if ($cart['Cart']['product_id'] > 0):
                        $i = 0;
                        $blockCountries = $this->BlockCountry->find('all', array('conditions' => array('BlockCountry.seller_id' => $cart['Product']['user_id'])));
                        foreach ($blockCountries as $blockCountry) {
                            if (array_search($this->Auth->user('country_id'), $blockCountry['Country']) !== FALSE) {
                                $this->Cart->delete($cart['Cart']['id']);
                                $this->Session->setFlash('Products Blocked for your country has removed');
                                $i++;
                            }
                        }
                        if ($i == 0) {
                            $this->data['Cart']['user_id'] = $this->Auth->User('id');
                            $this->data['Cart']['id'] = $cart['Cart']['id'];
                            $this->data['Cart']['product_cost'] = $cart['Cart']['product_cost'];
                            $this->data['Cart']['add_date'] = date("Y-m-d H:i:s");
                            $this->data['Cart']['status'] = 1;
                            $this->Cart->create();
                            $this->Cart->save($this->data);
                        }
                    endif;
                endforeach;
            }
        }
        //-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
        if ($this->Auth->user()) {
            if (!empty($this->data) && !empty($this->data['User']['remember_me'])) {
                $cookie = array();
                $cookie['username'] = $this->data['User']['username'];
                $cookie['password'] = $this->data['User']['password'];
                $this->Cookie->write('Auth.User', $cookie, true, '+4 weeks');
                unset($this->data['User']['remember_me']);
                //Update user cart information					
            }
            $this->redirect(array('controller' => 'users', 'action' => 'common'));
        }
        if (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //  Clear auth message, just in case we use it.
                    $this->Session->delete('Message.auth');
                    $this->redirect(array('controller' => 'users', 'action' => 'common'));
                } else { // Delete invalid Cookie
                    $this->Cookie->delete('Auth.User');
                }
            }
        }
    }

    function popup_login() {
        $this->layout = null;
        if (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //Clear auth message, just in case we use it.
                    $this->Session->delete('Message.auth');
                    $this->redirect(array('controller' => 'users', 'action' => 'common'));
                } else { // Delete invalid Cookie
                    $this->Cookie->delete('Auth.User');
                }
            }
        }
    }

    function genRandomString() {
        $length = 6;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

    function forget_password() {
        $this->layout = FALSE;
        if (!empty($this->data)) {
            $chk = $this->User->find('count', array('conditions' => array('User.username' => $this->data['User']['username'], 'User.email' => $this->data['User']['email'], 'User.dateofbirth' => $this->data['User']['dateofbirth'])));
            if ($chk > 0) {
                //$rand = $this->genRandomString();
                $users = $this->User->find('first', array('conditions' => array('User.username' => $this->data['User']['username'], 'User.email' => $this->data['User']['email'], 'User.dateofbirth' => $this->data['User']['dateofbirth']), 'fields' => array('User.id','User.hash_p'), 'recursive' => 0));
                $this->User->id = $users['User']['id'];
               //$this->User->saveField('password', $this->Auth->password($rand));
                $this->Email->to = $this->data['User']['email'];
                //$this->Email->bcc = array('secret@example.com');
                $this->Email->subject = 'Password of Authentic Avenue!';
                $this->Email->replyTo = 'noreply@authenticavenue.com';
                $this->Email->from = 'Authentic Team<info@authenticavenue.com>';
                $this->Email->template = 'forgetpassword'; // note no '.ctp'
                //Send as 'html', 'text' or 'both' (default is 'text')
                $this->Email->sendAs = 'html'; // because we like to send pretty mail
                //Set view variables as normal
                $this->set('username', $this->data['User']['username']);
                $this->set('password', $this->data['User']['hash_p']);
                //Do not pass any args to send()
                $this->Email->send();
                $this->render('pass_success');
            } else {
                $this->render('pass_fail');
            }
        }
    }

    function backstage_login() {
        $this->layout = 'admin';
    }

    function logout() {
        $cookie = $this->Cookie->read('Auth.User');
        if (!is_null($cookie)) {
            $this->Cookie->delete('Auth.User');
        }
        $this->Session->setFlash('You have been successfully logged out from the system.');
        $this->redirect($this->Auth->logout());
    }

    function build_acl() {
        if (!Configure::read('debug')) {
            return $this->_stop();
        }
        $log = array();

        $aco = & $this->Acl->Aco;
        $root = $aco->node('controllers');
        if (!$root) {
            $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
            $root = $aco->save();
            $root['Aco']['id'] = $aco->id;
            $log[] = 'Created Aco node for controllers';
        } else {
            $root = $root[0];
        }

        App::import('Core', 'File');
        $Controllers = Configure::listObjects('controller');
        $appIndex = array_search('App', $Controllers);
        if ($appIndex !== false) {
            unset($Controllers[$appIndex]);
        }
        $baseMethods = get_class_methods('Controller');
        $baseMethods[] = 'buildAcl';

        $Plugins = $this->_getPluginControllerNames();
        $Controllers = array_merge($Controllers, $Plugins);

        // look at each controller in app/controllers
        foreach ($Controllers as $ctrlName) {
            $methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

            // Do all Plugins First
            if ($this->_isPlugin($ctrlName)) {
                $pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
                if (!$pluginNode) {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
                    $pluginNode = $aco->save();
                    $pluginNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
                }
            }
            // find / make controller node
            $controllerNode = $aco->node('controllers/' . $ctrlName);
            if (!$controllerNode) {
                if ($this->_isPlugin($ctrlName)) {
                    $pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
                    $aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
                } else {
                    $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
                    $controllerNode = $aco->save();
                    $controllerNode['Aco']['id'] = $aco->id;
                    $log[] = 'Created Aco node for ' . $ctrlName;
                }
            } else {
                $controllerNode = $controllerNode[0];
            }

            //clean the methods. to remove those in Controller and private actions.
            foreach ($methods as $k => $method) {
                if (strpos($method, '_', 0) === 0) {
                    unset($methods[$k]);
                    continue;
                }
                if (in_array($method, $baseMethods)) {
                    unset($methods[$k]);
                    continue;
                }
                $methodNode = $aco->node('controllers/' . $ctrlName . '/' . $method);
                if (!$methodNode) {
                    $aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
                    $methodNode = $aco->save();
                    $log[] = 'Created Aco node for ' . $method;
                }
            }
        }
        if (count($log) > 0) {
            debug($log);
        }
    }

    function _getClassMethods($ctrlName = null) {
        App::import('Controller', $ctrlName);
        if (strlen(strstr($ctrlName, '.')) > 0) {
            // plugin's controller
            $num = strpos($ctrlName, '.');
            $ctrlName = substr($ctrlName, $num + 1);
        }
        $ctrlclass = $ctrlName . 'Controller';
        $methods = get_class_methods($ctrlclass);

        // Add scaffold defaults if scaffolds are being used
        $properties = get_class_vars($ctrlclass);
        if (array_key_exists('scaffold', $properties)) {
            if ($properties['scaffold'] == 'admin') {
                $methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
            } else {
                $methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
            }
        }
        return $methods;
    }

    function _isPlugin($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) > 1) {
            return true;
        } else {
            return false;
        }
    }

    function _getPluginControllerPath($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0] . '.' . $arr[1];
        } else {
            return $arr[0];
        }
    }

    function _getPluginName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[0];
        } else {
            return false;
        }
    }

    function _getPluginControllerName($ctrlName = null) {
        $arr = String::tokenize($ctrlName, '/');
        if (count($arr) == 2) {
            return $arr[1];
        } else {
            return false;
        }
    }

    function _getPluginControllerNames() {
        App::import('Core', 'File', 'Folder');
        $paths = Configure::getInstance();
        $folder = & new Folder();
        $folder->cd(APP . 'plugins');
        // Get the list of plugins
        $Plugins = $folder->read();
        $Plugins = $Plugins[0];
        $arr = array();
        // Loop through the plugins
        foreach ($Plugins as $pluginName) {
            // Change directory to the plugin
            $didCD = $folder->cd(APP . 'plugins' . DS . $pluginName . DS . 'controllers');
            // Get a list of the files that have a file name that ends
            // with controller.php
            $files = $folder->findRecursive('.*_controller\.php');
            // Loop through the controllers we found in the plugins directory
            foreach ($files as $fileName) {
                // Get the base file name
                $file = basename($fileName);
                // Get the controller name
                $file = Inflector::camelize(substr($file, 0, strlen($file) - strlen('_controller.php')));
                if (!preg_match('/^' . Inflector::humanize($pluginName) . 'App/', $file)) {
                    if (!App::import('Controller', $pluginName . '.' . $file)) {
                        debug('Error importing ' . $file . ' for plugin ' . $pluginName);
                    } else {
                        /// Now prepend the Plugin name ...
                        // This is required to allow us to fetch the method names.
                        $arr[] = Inflector::humanize($pluginName) . "/" . $file;
                    }
                }
            }
        }
        return $arr;
    }

    function initDB() {
        $group = & $this->User->Group;
        //Allow admins to everything
        $group->id = 1;
        $this->Acl->allow($group, 'controllers');
        //allow managers to posts and widgets
        $group->id = 2;
        $this->Acl->deny($group, 'controllers');
        $this->Acl->allow($group, 'controllers/users/index');
        $this->Acl->allow($group, 'controllers/users/backstage_deshboard');
        $this->Acl->allow($group, 'controllers/users/add');
        $this->Acl->allow($group, 'controllers/users/edit');
        $group->id = 3;
        $this->Acl->deny($group, 'controllers');
        $this->Acl->allow($group, 'controllers/users/index');
        $this->Acl->allow($group, 'controllers/users/backstage_deshboard');
        $this->Acl->allow($group, 'controllers/users/add');
        $group->id = 4;
        $this->Acl->deny($group, 'controllers');
        $this->Acl->allow($group, 'controllers/users/index');
        $this->Acl->allow($group, 'controllers/users/backstage_deshboard');
    }

    function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function brandcheck($id, $style, $uid=null) {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $isexist = $this->BrandPermission->findAllByBrandId($id);
        if (count($isexist) > 0) {
            $usernames = null;
            if ($uid == null) {
                foreach ($isexist as $user):
                    $usernames.=$user['User']['username'] . ', ';
                endforeach;
                echo 'This ' . $style . ' is also assigned for the following users: ' . $usernames;
            }else {

                if (count($isexist) != 1) {
                    foreach ($isexist as $user):
                        if ($user['User']['id'] != $uid) {
                            $usernames.=$user['User']['username'] . ', ';
                        }
                    endforeach;
                    echo 'This ' . $style . ' is also assigned for the following users: ' . $usernames;
                }
            }
        }
    }

    function add() {
        $this->layout = '';
        if (!empty($this->data)) {
            $this->data['User']['username'] = $_POST['username'];
            //$this->data['User']['password']=$this->Auth->hashPasswords($_POST['password']);
            $this->data['User']['password'] = $_POST['password'];
            $t = $this->Auth->hashPasswords($this->data);
            $this->data['User']['password'] = $t['User']['password'];
            $this->data['User']['group_id'] = '2';
            $this->data['User']['address'] = $this->data['address'];
            $this->data['User']['address2'] = $this->data['address1'];
            $this->data['User']['primary_phone'] = $this->data['phone1'];
            $this->data['User']['phone2'] = $this->data['phone2'];
            $this->data['User']['phone3'] = $this->data['phone3'];
            $this->data['User']['email'] = $_POST['email'];
            $this->data['User']['active'] = 1;
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            $this->User->create();
            if ($this->User->save($this->data)) {
                $uid = $this->User->getlastinsertid();
                // $this->Session->setFlash(__('The User has been saved.', true));
                if (!empty($this->data['User']['brandsid'])) {
                    $brandid = explode(',', $this->data['User']['brandsid']);
                    foreach ($brandid as $bid):
                        $this->data['BrandPermission']['id'] = null;
                        $this->data['BrandPermission']['user_id'] = $uid;
                        $this->data['BrandPermission']['brand_id'] = $bid;
                        $this->BrandPermission->save($this->data);
                    endforeach;
                }
                ////////////style////
                if (!empty($this->data['User']['styleid'])) {
                    $brandid = explode(',', $this->data['User']['styleid']);
                    foreach ($brandid as $bid):
                        $this->data['BrandPermission']['id'] = null;
                        $this->data['BrandPermission']['user_id'] = $uid;
                        $this->data['BrandPermission']['brand_id'] = $bid;
                        $this->BrandPermission->save($this->data);
                    endforeach;
                }
                ////////////Conditionsid////
                if (!empty($this->data['User']['conditionsid'])) {
                    $brandid = explode(',', $this->data['User']['conditionsid']);
                    foreach ($brandid as $bid):
                        $this->data['BrandPermission']['id'] = null;
                        $this->data['BrandPermission']['user_id'] = $uid;
                        $this->data['BrandPermission']['brand_id'] = $bid;
                        $this->BrandPermission->save($this->data);
                    endforeach;
                }
                $this->redirect(array('action' => 'addsuccess'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        $this->data['global_brand'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'brand')));
        $this->data['global_style'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'style')));
        $this->data['global_condition'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'condition')));
        $cities = $this->User->City->find('list', array('conditions' => array('City.country_id' => 223, 'City.state_id' => 3435), 'fields' => array('City.name'), 'order' => array('City.name')));
        $states = $this->User->State->find('list', array('conditions' => array('State.country_id' => 223), 'fields' => array('State.name'), 'order' => array('State.name')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'cities', 'states', 'countries'));
    }

    function add_superadmin() {
        $this->layout = '';
        if (!empty($this->data)) {
            $this->data['User']['username'] = $_POST['username'];
            $this->data['User']['password'] = $_POST['password'];
            $t = $this->Auth->hashPasswords($this->data);
            $this->data['User']['password'] = $t['User']['password'];
            $this->data['User']['group_id'] = '1';
            $this->data['User']['address'] = $this->data['address'];
            $this->data['User']['address2'] = $this->data['address1'];
            $this->data['User']['primary_phone'] = $this->data['phone1'];
            $this->data['User']['phone2'] = $this->data['phone2'];
            $this->data['User']['phone3'] = $this->data['phone3'];
            $this->data['User']['email'] = $_POST['email'];
            $this->data['User']['active'] = 1;
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            /*
              if(isset($this->data['global_brand']))
              $this->data['User']['brandsid'] = implode(",", $this->data['global_brand']);
              if(isset($this->data['global_style']))
              $this->data['User']['styleid'] = implode(",", $this->data['global_style']);
              if(isset($this->data['global_condition']))
              $this->data['User']['conditionsid'] = implode(",", $this->data['global_condition']);
             */
            $this->User->create();
            if ($this->User->save($this->data)) {
                // $this->Session->setFlash(__('The User has been saved.', true));
                $this->render('add_super_success');
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        //$groups = $this->User->Group->find('list');
        /* $this->data['global_brand'] = $this->Brand->find('all',array('conditions'=>array('Brand.brand_type'=>'brand')));
          $this->data['global_style'] = $this->Brand->find('all',array('conditions'=>array('Brand.brand_type'=>'style')));
          $this->data['global_condition'] = $this->Brand->find('all',array('conditions'=>array('Brand.brand_type'=>'condition')));
         */
        $states = $this->User->State->find('list', array('fields' => array('State.state'), 'order' => array('State.state')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'states', 'countries'));
    }

    function usercheck() {
        $this->layout = '';
        $username = $_POST['username'];
        $check = $this->User->find('count', array('conditions' => array('User.username' => $username)));
        if ($check == 0)
            echo 'true';
        die();
    }

    function capcheck() {
        $this->layout = false;
        $this->autoRender = FALSE;
        if ($_POST['cap2'] == $this->Session->read('captcha'))
            echo 'true';
    }

    function emailcheck() {
        $this->layout = '';
        $email = $_POST['email'];
        $check = $this->User->find('count', array('conditions' => array('User.email' => $email)));
        if ($check == 0)
            echo 'true';
        die();
    }

    function edit($id = null) {

        $this->layout = '';
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if (!empty($this->data['User']['brandsid'])) {
                $brandid = explode(',', $this->data['User']['brandsid']);
                foreach ($brandid as $bid):
                    $this->data['BrandPermission']['id'] = null;
                    $this->data['BrandPermission']['user_id'] = $this->data['User']['id'];
                    $this->data['BrandPermission']['brand_id'] = $bid;
                    $isexist = $this->BrandPermission->find('count', array('conditions' => array('BrandPermission.brand_id' => $bid, 'BrandPermission.user_id' => $this->data['User']['id'])));
                    if ($isexist == 0) {
                        $this->BrandPermission->save($this->data);
                    }
                endforeach;
            }

            ////////////style////
            if (!empty($this->data['User']['styleid'])) {
                $brandid = explode(',', $this->data['User']['styleid']);
                foreach ($brandid as $bid):
                    $this->data['BrandPermission']['id'] = null;
                    $this->data['BrandPermission']['user_id'] = $this->data['User']['id'];
                    $this->data['BrandPermission']['brand_id'] = $bid;
                    $isexist = $this->BrandPermission->find('count', array('conditions' => array('BrandPermission.brand_id' => $bid, 'BrandPermission.user_id' => $this->data['User']['id'])));
                    if ($isexist == 0) {
                        $this->BrandPermission->save($this->data);
                    }
                endforeach;
            }

            ////////////Conditionsid////
            if (!empty($this->data['User']['conditionsid'])) {
                $brandid = explode(',', $this->data['User']['conditionsid']);
                foreach ($brandid as $bid):
                    $this->data['BrandPermission']['id'] = null;
                    $this->data['BrandPermission']['user_id'] = $this->data['User']['id'];
                    $this->data['BrandPermission']['brand_id'] = $bid;
                    $isexist = $this->BrandPermission->find('count', array('conditions' => array('BrandPermission.brand_id' => $bid, 'BrandPermission.user_id' => $this->data['User']['id'])));
                    if ($isexist == 0) {
                        $this->BrandPermission->save($this->data);
                    }
                endforeach;
            }

            if (!empty($_POST['password'])) {

                $this->data['User']['password'] = $_POST['password'];
                $this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
            }
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            if ($this->User->save($this->data)) {
                //$this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'editsuccess'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $this->BrandPermission->recursive = -1;
        $globales = $this->BrandPermission->findAllByUserId($id);
        $this->set('globales', $globales);
        /* if(isset($this->data['User']['styleid']))
          $this->data['globalst'] = explode(",", $this->data['User']['styleid']);
          if(isset($this->data['User']['conditionsid']))
          $this->data['globalcon'] = explode(",", $this->data['User']['conditionsid']); */
        //$groups = $this->User->Group->find('list');
        $this->data['global_brand'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'brand')));
        $this->data['global_style'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'style')));
        $this->data['global_condition'] = $this->Brand->find('all', array('conditions' => array('Brand.brand_type' => 'condition')));


        $states = $this->User->State->find('list', array('fields' => array('State.state'), 'order' => array('State.state')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'states', 'countries'));
    }

    function seller_account($id = null) {
        $this->layout = '';
        if (empty($this->data)) {
            $this->User->unbindModel(array('hasMany' => array('Product', 'MessageTrackReceived', 'MessageTrackSent', 'BrandPermission')));
            $this->data = $this->User->read(null, $id);
            //pr($this->data);
        }
    }

    function editqadmin() {
        $this->layout = 'admin';

        $id = $this->Auth->user('id');
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'editqadmin'));
        }
        if (!empty($this->data)) {
            if (!empty($_POST['password'])) {
                $this->data['User']['password'] = $_POST['password'];
                $this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
            }
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The information has been updated.', true));
                $this->redirect(array('action' => 'editqadmin'));
            } else {
                $this->Session->setFlash(__('The information could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $states = $this->User->State->find('list', array('fields' => array('State.state'), 'order' => array('State.state')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'states', 'countries'));
    }

    function backstage_editqadmin() {
        $this->layout = 'admin';
        $id = $this->Auth->user('id');
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'editqadmin'));
        }
        if (!empty($this->data)) {
            if (!empty($_POST['password'])) {
                $this->data['User']['password'] = $_POST['password'];
                $this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
            }
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The information has been updated.', true));
                $this->redirect(array('action' => 'editqadmin'));
            } else {
                $this->Session->setFlash(__('The information could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->User->unbindModel(array('hasMany' => array('Product', 'MessageTrackReceived', 'MessageTrackSent', 'BrandPermission')));
            $this->data = $this->User->read(null, $id);
            //pr($this->data);
        }

        $cities = $this->User->City->find('list', array('conditions' => array('City.country_id' => $this->data['User']['country_id'], 'City.state_id' => $this->data['User']['state_id']), 'fields' => array('City.name'), 'order' => array('City.name')));
        $states = $this->User->State->find('list', array('conditions' => array('State.country_id' => $this->data['User']['country_id']), 'fields' => array('State.name'), 'order' => array('State.name')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'cities', 'states', 'countries'));
    }

    function my_information() {
        $this->layout = 'innerhome';

        $id = $this->Auth->user('id');
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'login'));
        }
        if (!empty($this->data)) {
            if (!empty($_POST['password'])) {
                $this->data['User']['hash_p'] = $_POST['password'];
                $this->data['User']['password'] = $_POST['password'];
                $this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
            }
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The information has been updated.', true));
            } else {
                $this->Session->setFlash(__('The information could not be saved. Please, try again.', true));
            }
        }
        $this->User->unbindModel(array('hasMany' => array('Product', 'MessageTrackReceived', 'MessageTrackSent', 'BrandPermission')));
        $this->data = $this->User->read(null, $id);
        $cities = $this->User->City->find('list', array('conditions' => array('City.state_id' => $this->data['User']['state_id']), 'fields' => array('City.name'), 'order' => array('City.name')));
        $states = $this->User->State->find('list', array('conditions' => array('State.country_id' => $this->data['User']['country_id']), 'fields' => array('State.name'), 'order' => array('State.name')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $this->set(compact('secretquestions', 'cities', 'states', 'countries'));
    }

    function backstage_delete($id = null) {

        if (!$id) {
            $this->Session->setFlash(__('Invalid id for User', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->data['User']['id'] = $id;
        $this->data['User']['active'] = 2;
        if ($this->User->save($this->data)) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
    }

    function backstage_sellersearch($sk=null, $type=null) {
        $this->layout = 'admin';
        $this->User->recursive = 0;
        if (!empty($this->data)) {
            if ($this->data['type'] == '') {
                $this->redirect(array('action' => 'seller'));
            } elseif ($this->data['type'] == 'id') {
                $this->paginate = array(
                    'User' => array('limit' => 100, 'conditions' => array('Group.group_type' => array('Sellers'),
                            'User.username like' => '%' . $this->data['searchkey'] . '%', 'User.active >' => 0))
                );
            } elseif ($this->data['type'] == 'name') {
                $this->paginate = array(
                    'User' => array('limit' => 100,
                        'conditions' => array('Group.group_type' => array('Sellers'), 'User.first_name like' => '%' . $this->data['searchkey'] . '%', 'User.active >' => 0))
                );
            } elseif ($this->data['type'] == 'email') {
                $this->paginate = array(
                    'User' => array('limit' => 100, 'conditions' => array('Group.group_type' => array('Sellers'), 'User.email like' => '%' . $this->data['searchkey'] . '%', 'User.active >' => 0))
                );
            }

            $this->set('sk', $this->data['searchkey']);
            $this->set('type', $this->data['type']);
        } else {
            if ($type == 'id') {
                $this->paginate = array(
                    'User' => array('limit' => 100, 'conditions' => array('Group.group_type' => array('Sellers'),
                            'User.username like' => '%' . $sk . '%', 'User.active >' => 0))
                );
            } elseif ($type == 'name') {
                $this->paginate = array(
                    'User' => array('limit' => 100,
                        'conditions' => array('Group.group_type' => array('Sellers'), 'User.first_name like' => '%' . $sk . '%', 'User.active >' => 0))
                );
            } elseif ($type == 'email') {
                $this->paginate = array(
                    'User' => array('limit' => 100, 'conditions' => array('Group.group_type' => array('Sellers'), 'User.email like' => '%' . $sk . '%', 'User.active >' => 0))
                );
            }
        }

        $this->set('users', $this->paginate('User'));
        $groups = $this->User->Group->find('list', array('conditions' => array('Group.group_type' => array('Sellers'))));
        //$groups = $this->User->Group->find('list',array('conditions' => array('Group.id' => array('3','5','6','7')) ));
        $this->set(compact('groups'));
        if ($sk != null)
            $this->set('sk', $sk);
        if ($sk != null)
            $this->set('type', $type);
    }

    function backstage_index() {
        $this->layout = 'admin';
        $this->User->recursive = 0;
        $this->paginate = array(
            'User' => array('limit' => 10, 'conditions' => array('User.group_id' => 2, 'User.active' => 1))
        );
        $this->set('users', $this->paginate());
    }

    function backstage_seller() {
        $this->layout = 'admin';
        $this->User->recursive = 0;
        $this->paginate = array(
            'User' => array('limit' => 25, 'conditions' => array('Group.group_type' => array("Sellers"), 'User.active >' => 0))
        );
        $this->set('users', $this->paginate());
        $groups = $this->User->Group->find('list', array('conditions' => array('Group.group_type' => array('Sellers'))));
        $this->set(compact('groups'));
    }

    function backstage_manageuser() {
        $this->layout = 'admin';
        $this->User->recursive = 0;
        $this->paginate = array(
            'User' => array('order' => 'created DESC', 'limit' => 25, 'conditions' => array('Group.group_type' => array("Sellers", "Q-Admins", "Buyers"), 'User.active >' => 0))
        );
        $this->set('users', $this->paginate());
        $groups = $this->User->Group->find('list', array('conditions' => array('Group.group_type' => array("Sellers", "Q-Admins", "Buyers"))));
        $this->set(compact('groups'));
    }

    function changelevel($id, $level) {
        $this->layout = '';
        $this->autoRender = FALSE;
        $this->User->id = $id;
        $this->User->saveField('group_id', $level);
        return true;
    }

    function addsuccess() {
        $this->layout = false;
    }

    function buyersuccess() {
        $this->layout = false;
    }

    function editsuccess() {
        $this->layout = false;
    }

    function captcha($st=null) {
        $this->layout = false;
        $this->Captcha->render();
        $this->autoRender = false;
    }

    function brandaccess() {
        $this->layout = false;
        $this->autoRender = false;
        $return_array['ddd'] = 'ddd';
        if (isset($this->data['global_brand']))
            $return_array['hdIDValue'] = implode(',', $this->data['global_brand']);
        if (isset($this->data['global_style']))
            $return_array['hdIDValuest'] = implode(',', $this->data['global_style']);
        if (isset($this->data['global_condition']))
            $return_array['hdIDValuecon'] = implode(',', $this->data['global_condition']);
        return json_encode($return_array);
    }

    function register() {
        $this->layout = '';
        if (!empty($this->data)) {
            $this->data['User']['username'] = $_POST['username'];
            $this->data['User']['password'] = $_POST['password'];
            $this->data['User']['hash_p'] = $_POST['password'];
            $t = $this->Auth->hashPasswords($this->data);
            $this->data['User']['password'] = $t['User']['password'];
            //$this->data['User']['group_id']='4';
            $this->data['User']['address'] = $this->data['address'];
            $this->data['User']['address2'] = $this->data['address1'];
            $this->data['User']['primary_phone'] = $this->data['phone1'];
            $this->data['User']['phone2'] = $this->data['phone2'];
            $this->data['User']['phone3'] = $this->data['phone3'];
            $this->data['User']['email'] = $_POST['email'];
            $this->data['User']['active'] = 0;
            $this->data['User']['ques_ans'] = base64_encode($this->data['User']['ques_ans']);
            $this->User->create();

            if ($this->User->save($this->data)) {
                //$group=$this->Group->findById($this->data['User']['group_id']);
                $user_id = $this->User->getLastInsertId();
                /////////////messages center/////////
                $this->loadModel('MessageTrack');
                $this->data['Message']['subject'] = "Welcome to Authentic Avenue!";
                $this->data['Message']['message'] = "<p>Hi " . $_POST['username'] . "</p><p>Thanks for joining us on Authentic Avenue!</p><p>Thank you,</p><p>Authentic Avenue</p>";
                $this->Message->create();
                if ($this->Message->save($this->data)) {
                    $mid = $this->Message->getLastInsertID();
                    /////////for sent item//////
                    $this->data['MessageTrack']['id'] = null;
                    $this->data['MessageTrack']['message_id'] = $mid;
                    $this->data['MessageTrack']['to_id'] = $user_id;
                    $this->data['MessageTrack']['from_id'] = 1;
                    $this->data['MessageTrack']['msg_type'] = 0;
                    $this->data['MessageTrack']['read'] = 0;
                    $this->data['MessageTrack']['star'] = 0;
                    $this->data['MessageTrack']['reply'] = 0;
                    $this->MessageTrack->save($this->data);
                    ///////////for inbox///////
                    $this->data['MessageTrack']['id'] = null;
                    $this->data['MessageTrack']['message_id'] = $mid;
                    $this->data['MessageTrack']['to_id'] = $user_id;
                    $this->data['MessageTrack']['from_id'] = 1;
                    $this->data['MessageTrack']['msg_type'] = 1;
                    $this->data['MessageTrack']['read'] = 0;
                    $this->data['MessageTrack']['star'] = 0;
                    $this->data['MessageTrack']['reply'] = 0;
                    $this->MessageTrack->save($this->data);
                }
                ////////for send email////////
                $this->Email->to = $_POST['email'];
                //$this->Email->bcc = array('secret@example.com');
                $this->Email->subject = 'Welcome to Authentic Avenue!';
                //$this->Email->replyTo = 'noreply@authenticavenue.com';
                $this->Email->from = 'info@authenticavenue.com';
                $this->Email->template = 'registration'; // note no '.ctp'
                //Send as 'html', 'text' or 'both' (default is 'text')
                $this->Email->sendAs = 'html'; // because we like to send pretty mail
                //Set view variables as normal            
                $this->set('username', $_POST['username']);
                $this->set('password', $_POST['password']);
                $this->set('email', $_POST['email']);
                $this->set('userid', $user_id);
                $this->Email->send();
                //if($group['Group']['group_type']=='Sellers'){
                $this->loadModel('Paymentmethod');

                $this->data['Paymentmethod']['user_id'] = $user_id;
                $this->data['Paymentmethod']['methodname'] = 'Paypal';
                $this->Paymentmethod->save($this->data);
                $this->data['Paymentmethod']['user_id'] = $user_id;
                $this->data['Paymentmethod']['methodname'] = 'Google Checkout';
                $this->Paymentmethod->create();
                $this->Paymentmethod->save($this->data);
                //}
                $this->redirect(array('action' => 'buyersuccess'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        $cities = $this->User->City->find('list', array('conditions' => array("City.country_id" => 223, "City.state_id" => 3435), 'fields' => array('City.name'), 'order' => array('City.name ASC')));
        $states = $this->User->State->find('list', array('conditions' => array("State.country_id" => 223), 'fields' => array('State.name'), 'order' => array('State.name ASC')));
        $countries = $this->User->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));
        $secretquestions = $this->User->Secretquestion->find('list', array('fields' => array('Secretquestion.secretquestions')));
        $groups = $this->Group->find('list', array(
            'fields' => array('Group.id', 'Group.name', 'Group.group_type'),
            'conditions' => array('NOT' => array(array('Group.group_type' => array('S-Admins', 'Q-Admins')))),
            'recursive' => 0
                ));

        $this->set(compact('secretquestions', 'cities', 'states', 'countries', 'groups'));
    }

    function backstage_add() {
        if (!empty($this->data)) {
            $this->data['User']['group_id'] = 5;
            $this->User->create();
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The user has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }
        $groups = $this->User->Group->find('list');
        $secretquestions = $this->User->Secretquestion->find('list');
        $this->set(compact('groups', 'secretquestions'));
    }

    function suspend($id=null) {
        $this->layout = '';
        if (!empty($this->data)) {
            $this->User->id = $id;
            $this->data['User']['active'] = 2;
            $this->data['User']['suspend_reason'] = $this->data['suspend'];
            $this->User->save($this->data);
            $this->redirect(array('action' => 'suspendsuccess'));
        }
        $this->set('id', $id);
    }

    function reactive($id=null) {
        $this->layout = '';
        if (!empty($this->data)) {
            $this->User->id = $id;
            $this->data['User']['active'] = 1;
            $this->data['User']['suspend_reason'] = '';
            $this->User->save($this->data);
            $this->redirect(array('action' => 'reactivesuccess'));
        }
        $this->data = $this->User->read(array('id', 'suspend_reason'), $id);
    }

    function activateuser($id=null) {
        $this->layout = 'innerhome';

        $this->loadModel('Category');
        $this->loadModel('Product');
        $this->set('item', $this->Category->categoryArray());
        $userinfo = $this->User->read($id);

        if ($userinfo['User']['activatecheck'] == 0) {
            $this->User->id = $id;
            $this->data['User']['active'] = 1;
            $this->data['User']['activatecheck'] = 1;
            $this->data['User']['suspend_reason'] = '';
            $this->User->save($this->data);
        }
    }

    function suspendsuccess() {
        $this->layout = false;
    }

    function reactivesuccess() {
        $this->layout = false;
    }

    function getusername($id=null) {
        $this->layout = false;
        $this->autoRender = FALSE;
        $this->User->recursive = -1;
        $uinfo = $this->User->read('username', $id);
        return $uinfo['User']['username'];
    }

    function my_address_book() {
        //loading layout
        $this->layout = 'innerhome';
        $proced = FALSE;
        if (isset($_SERVER['HTTP_REFERER'])) {
            $proced = end(explode("/", $_SERVER['HTTP_REFERER'])) == "view_cart" ? TRUE : FALSE;
        }
        $this->set('proced', $proced);
        //user id
        $userId = $this->Auth->user('id');
        //loading models
        $this->loadModel('AddressBook');
        $this->loadModel('AddressBookField');
        $addresses = $this->AddressBook->find('all', array('conditions' => array('AddressBook.user_id' => $userId)));
        $cities = $this->AddressBookField->City->find('list', array('conditions' => array("City.country_id" => 223, "City.state_id" => 3435), 'fields' => array('City.name'), 'order' => array('City.name')));
        $states = $this->AddressBookField->State->find('list', array('conditions' => array('State.country_id' => 223), 'fields' => array('State.name'), 'order' => array('State.name')));
        $countries = $this->AddressBookField->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));

        $this->set(compact('addresses', 'cities', 'states', 'countries'));
    }

    function my_address_book_save() {
        $this->layout = false;
        //loading models
        $this->loadModel('AddressBook');
        $this->loadModel('AddressBookField');
        if (!empty($this->data)) {
            $this->data['AddressBook']['user_id'] = $this->Auth->user('id');
            $this->AddressBook->saveAll($this->data);
            //$this->set('countries', $this->Country->find('all', array('order' => array('Country.name ASC'))));
            //returing saved data
            $lastInsertId = isset($this->data['AddressBook']['id']) ? $this->data['AddressBook']['id'] : $this->AddressBook->getLastInsertId();
            $address = $this->AddressBook->find('first', array('conditions' => array('AddressBook.id' => $lastInsertId)));
            $cities = $this->AddressBookField->City->find('list', array('conditions' => array("City.country_id" => $address['AddressBookField']['country_id'], "City.state_id" => $address['AddressBookField']['state_id']), 'fields' => array('City.name'), 'order' => array('City.name')));
            $states = $this->AddressBookField->State->find('list', array('conditions' => array('State.country_id' => $address['AddressBookField']['country_id']), 'fields' => array('State.name'), 'order' => array('State.name')));
            $countries = $this->AddressBookField->Country->find('list', array('fields' => array('Country.name'), 'order' => array('Country.name ASC')));

            $this->set(compact('address', 'cities', 'states', 'countries'));
        }
    }

    function my_address_book_delete() {
        $this->loadModel('AddressBook');
        $this->loadModel('AddressBookField');
        $this->AddressBook->delete($this->data['AddressBook']['id']);
        $this->AddressBookField->delete($this->data['AddressBookField']['id']);
        $this->layout = false;
        $this->autoRender = FALSE;
    }

    function my_address_book_select($id) {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('AddressBook');
        //remove previously selected
        $yesId = $this->AddressBook->find('first', array('conditions' => array('AddressBook.user_id' => $this->Auth->user('id'), 'AddressBook.use_in_cart' => "yes")));
        $this->AddressBook->id = $yesId['AddressBook']['id'];
        $this->AddressBook->saveField('use_in_cart', 'no');
        $this->data['AddressBook']['use_in_cart'] = "yes";
        $this->data['AddressBook']['id'] = $id;
        $this->AddressBook->save($this->data);
    }

    function getshipping_address() {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('AddressBook');
        $this->loadModel('AddressBookField');
        $this->AddressBook->recursive = 2;
        return $this->AddressBook->find('first', array('conditions' => array('AddressBook.user_id' => $this->Auth->User('id'), 'use_in_cart' => "yes")));
    
        
    }

    function add_to_favorite_seller() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('FavoriteSeller');
        //check if user add more than 100 seller
        $totalCheck = $this->FavoriteSeller->find('count', array('conditions' => array('FavoriteSeller.buyer_id' => $this->data['FavoriteSeller']['buyer_id'])));
        if ($totalCheck >= 100) {
            echo 'You cannot add more than 100 seller in your favorite list';
            return;
        }
        //check if user add this seller before
        $checkUnique = $this->FavoriteSeller->find('count', array('conditions' => array('FavoriteSeller.buyer_id' => $this->data['FavoriteSeller']['buyer_id'], 'FavoriteSeller.seller_id' => $this->data['FavoriteSeller']['seller_id'])));
        if ($checkUnique == 0) {
            $this->FavoriteSeller->save($this->data);
            //add to subscription
            $this->loadModel('Subscribe');
            $this->data['Subscribe']['seller_id'] = $this->data['FavoriteSeller']['seller_id'];
            $this->data['Subscribe']['buyer_id'] = $this->data['FavoriteSeller']['buyer_id'];
            $this->data['Subscribe']['period'] = 30;
            $this->Subscribe->save($this->data);
            echo 'Added to Favorite Seller';
            return;
        }
        echo 'Already Added to Favorite Seller';
    }

    function favorite_seller() {
        $this->layout = 'innerhome';
        $this->loadModel('FavoriteSeller');
        $this->loadModel('Subscribe');
        $sellers = $this->FavoriteSeller->allFavorites($this->Auth->user('id'));
        if (count($sellers) == 0) {
            $this->FavoriteSeller->insertFavorite($this->Auth->user('id'));
            $sellers = $this->FavoriteSeller->allFavorites($this->Auth->user('id'));
        }
        $this->set('sellers', $sellers);
    }

    function remove_favorite() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('FavoriteSeller');
        $this->loadModel('FavouriteNote');
        $this->FavoriteSeller->delete($this->data['FavoriteSeller']['id'], false);
        $this->FavouriteNote->deleteAll(array('favorite_sellers_id' => $this->data['FavoriteSeller']['id']));
    }

    function add_favorite_note($id) {
        $this->layout = FALSE;
        $this->set('ids', explode(',', $id));
    }

    function save_favorite_note() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('FavoriteSeller');
        $this->loadModel('FavouriteNote');
        $this->FavouriteNote->save($this->data);
    }

    function save_all_favorite() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('FavouriteNote');
        foreach ($_POST['id'] as $id) {
            $this->data['FavouriteNote']['favorite_sellers_id'] = $id;
            $this->data['FavouriteNote']['note'] = $_POST['note'];
            $this->FavouriteNote->id = NULL;
            $this->FavouriteNote->save($this->data);
        }
    }

    function toggleSubscribe() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('Subscribe');
        $this->Subscribe->save($this->data);
    }

    function backstage_qadmin_summary($id=null) {
        $this->layout = "admin";
        if (!empty($this->data['QadminSummary']['cheque_no'])) {
            $this->data['QadminSummary']['cheque_no'] = $this->data['QadminSummary']['cheque_no'];
            $this->data['QadminSummary']['status'] = "Paid";
            $this->data['QadminSummary']['pay_date'] = date("Y-m-d H:i:s");
            $this->QadminSummary->save($this->data);
        }

        $this->User->recursive = -1;
        $users = $this->User->findById($id);
        $this->paginate = array(
            'QadminSummary' => array('limit' => 10, 'conditions' => array('QadminSummary.user_id' => $id))
        );
        $this->set('users', $users);
        $this->set('summaries', $this->paginate('QadminSummary'));
    }

    function backstage_qadmin_sold($id=null) {
        $this->layout = "admin";
        $users = $this->QadminSummary->findById($id);
        $start_date = $users['QadminSummary']['period1'];
        $end_date = $users['QadminSummary']['period2'];
        $this->loadModel("Product");
        $this->loadModel("Order");
        $sell_products = $this->Product->find("list", array("conditions" => array("Product.approved_id" => $users['QadminSummary']['user_id']), "fields" => array("Product.id")));
        $this->Order->bindModel(
                array('belongsTo' => array(
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        )
                    )
                )
        );
        $this->Order->Behaviors->attach('Containable');
        $solds = $this->Order->find('all', array(
            'Contain' => array('Product', 'Order'),
            'conditions' => array("Order.product_id" => $sell_products, "Order.payment_status" => "Complete", "Order.add_date BETWEEN ? AND ?" => array($start_date, $end_date)),
            'group' => 'Product.id')
        );
        $this->set('users', $users);
        $this->set('solds', $solds);
    }

    function total_sold($id1=null, $id2=null, $id3=null) {
        $this->loadModel("Order");
        $start_date = date("Y-m-d H:i:s", $id2);
        $end_date = date("Y-m-d H:i:s", $id3);
        return $total_sell_products = $this->Order->find("count", array("conditions" => array("Order.product_id" => $id1, "Order.payment_status" => "Complete", "Order.add_date BETWEEN ? AND ?" => array($start_date, $end_date))));
        $this->autoRender = false;
    }

    function feedback($userid) {
        $this->layout = '';
        $this->loadModel('Rating');
        $this->set('productRating', $this->Rating->sadmincheckRating($userid));
    }

    //Load State List
    function loadState($id=null) {
        $this->layout = false;
        $this->State->recursive = -1;
        $states = $this->State->find('list', array('conditions' => array("State.country_id" => $id), 'fields' => array('State.name'), 'order' => array('State.name ASC')));
        $this->set(compact('states'));
    }

    //Load City List
    function loadCity($id=null) {
        $this->layout = false;
        $this->City->recursive = -1;
        $cities = $this->City->find('list', array('conditions' => array("City.state_id" => $id), 'fields' => array('City.name'), 'order' => array('City.name ASC')));
        $this->set(compact('cities'));
    }

    //Load State List
    function loadStateAddress($id=null, $id2=null, $id3=null) {
        $this->layout = false;
        $this->State->recursive = -1;
        $states = $this->State->find('list', array('conditions' => array("State.country_id" => $id), 'fields' => array('State.name'), 'order' => array('State.name ASC')));
        if (empty($id3))
            $this->set(compact('states', 'id2'));
        else
            $this->set(compact('states', 'id2', 'id3'));
    }

    //Load City List for address field
    function loadCityAddress($id=null, $id2=null, $id3=null) {
        $this->layout = false;
        $this->City->recursive = -1;
        $cities = $this->City->find('list', array('conditions' => array("City.state_id" => $id), 'fields' => array('City.name'), 'order' => array('City.name ASC')));
        if (empty($id3))
            $this->set(compact('cities', 'id2'));
        else
            $this->set(compact('cities', 'id2', 'id3'));
    }

}

?>